﻿using AutoMapper;
using ERPSystem.Common.Domains.SalesOrderCommom;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;

namespace SalesManagementWrite.API.SalesManagementWrites.SalesOrders
{
    public class SalesOrderMaterialCreateHander : IRequestHandler<SalesOrderMaterialCreateCommand, Result>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<SalesOrderMaterial> _salesOrderMaterialRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="salesOrderMaterialRepository"></param>
        public SalesOrderMaterialCreateHander(IMapper mapper, IBaseRepository<SalesOrderMaterial> salesOrderMaterialRepository)
        {
            _mapper = mapper;
            _salesOrderMaterialRepository = salesOrderMaterialRepository;
        }
        /// <summary>
        /// 处理创建销售订单物料命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SalesOrderMaterialCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                
                var list = await _salesOrderMaterialRepository.AddRange(request.SalesOrderMaterials);
                result.Data = list;
                if (list > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                }
                else
                {
                    result.Msg = "添加失败";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
